/* global window */
import { message } from 'antd'
import api from 'api'
import modelExtend from 'dva-model-extend'
import { pathMatchRegexp } from 'utils'
import { model } from 'utils/model'

const { getAllDeviceGeo, setNetWork, delNetWork, setChannel } = api

const regionstate = {
  points: {},
  project: 'all',
}

export default modelExtend(model, {
  namespace: 'loras',

  state: {
    ...regionstate,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathMatchRegexp('/loras', location.pathname)) {
          let payload = { project: 'all' }
          if (location.query) {
            const { project } = location.query
            payload = {
              ...payload,
              ...(project != undefined ? { project } : {}),
              // ...(filter ? { filter: JSON.parse(filter) } : {}),
            }
          }
          dispatch({
            type: 'updateState',
            payload: {
              project: payload.project,
            },
          })
          dispatch({
            type: 'query',
            payload,
          })
        }
      })
    },
  },

  effects: {
    *setChannel({ payload = {} }, { call, put, select }) {
      message.loading('修改中...', 0)
      const { result } = yield call(setChannel, payload)
      message.destroy()
      message.success('修改成功')
    },
    *delNetWork({ payload = {} }, { call, put, select }) {
      message.loading('删除中...', 0)
      const { result } = yield call(delNetWork, payload)
      message.destroy()
      message.success('删除成功')
    },
    *setNetWork({ payload = {} }, { call, put, select }) {
      message.loading('设置中...', 0)
      const { result } = yield call(setNetWork, payload)
      message.destroy()
      message.success('设置成功')
    },
    *clearstore({ payload = {} }, { call, put, select }) {
      yield put({
        type: 'updateState',
        payload: { ...regionstate },
      })
    },
    *query({ payload }, { call, put, select }) {
      const { project } = yield select(_ => _.loras)
      var ProjectId = payload && payload.project ? payload.project : project
      const { result } = yield call(getAllDeviceGeo, { ProjectId })
      yield put({
        type: 'updateState',
        payload: { points: result },
      })
    },
  },

  reducers: {},
})
